# -*- coding=utf-8 -*-

"""
fuwa model
"""
import cPickle
import os
import time
from framework.redi import RedisModel

class UFuwaModel(RedisModel):
    """user"""

    def __init__(self):
        """super init"""
        super(UFuwaModel, self).__init__()

    def get_fuwas_count(self, uid):
        """get fuwa count"""
        data = dict()
        data['applys'] = self.zcard('%s_fuwas' % uid)
        data['unused'] = self.scard('%s_apply' % uid)
        data['pack'] = self.scard('%s_pack' % uid)
        data['hiding'] = self.zscore('user_hide', uid)
        data['caut'] = self.zscore('user_caut', uid)
        data['awarded'] = self.zscore('user_awarded', uid)
        return data

    def get_fuwa_rank(self):
        """ fuwa rank """
        node_rank = dict()
        rank_cache = "rank.txt"
        expiry = 24 * 3600
        current_time = time.time()
        # check cache file
        try:
            mtime = os.path.getmtime(rank_cache)
            if (current_time - mtime) > expiry:
                mtime = 0
            else:
                with open(rank_cache) as fp:
                    node_rank = cPickle.load(fp)
        except OSError:
            mtime = 0
        if mtime == 0:
            j = 1
            for i in self.zrevrangebyscore('fuwa_rank', '+inf', '-inf', withscores=True):
                if j == 101:
                    break
                k = str(j)
                if node_rank.get(k, -1) == -1:
                    node_rank[k] = dict(users=set([i[0]]), num=int(i[1]))
                else:
                    t = node_rank.get(k)
                    if int(t.get('num')) == int(i[1]):
                        # if len(t['users']) > 3:
                        #    continue
                        t['users'].add(i[0])
                        # if user_id == i[0]:
                        #    current_rank = j
                    else:
                        j += 1
                        k = str(j)
                        node_rank[k] = dict(users=set([i[0]]), num=int(i[1]))
            # write to cache file
            with open(rank_cache, "w") as fp:
                cPickle.dump(node_rank, fp)
        return node_rank
